<!--
* @Description: 支付宝支付 - 表单
* @Author: DHL
* @Date: 2022-03-30 13:50:53
 * @LastEditors: DHL
 * @LastEditTime: 2023-01-06 10:01:28
-->
<template>
  <tw-drawer
    v-model="visible"
    title="支付宝支付配置"
    :loading="loading"
    size="50%"
    @close="handleClose"
  >
    <div class="form-wrapper">
      <el-form ref="dbFormRef" :model="dbForm" :rules="rules" label-width="120px">
        <el-form-item label="应用ID" prop="appId">
          <el-input v-model="dbForm.appId" clearable placeholder="请输入应用ID"></el-input>
        </el-form-item>

        <el-form-item label="协议" prop="protocol">
          <el-input v-model="dbForm.protocol" clearable placeholder="请输入协议"></el-input>
        </el-form-item>

        <el-form-item label="网管主机" prop="gatewayHost">
          <el-input v-model="dbForm.gatewayHost" clearable placeholder="请输入网管主机"></el-input>
        </el-form-item>

        <el-form-item label="签名类型" prop="signType">
          <el-input v-model="dbForm.signType" clearable placeholder="请输入签名类型"></el-input>
        </el-form-item>

        <el-form-item label="应用私钥" prop="privateKey">
          <el-input
            v-model="dbForm.privateKey"
            clearable
            :rows="5"
            type="textarea"
            placeholder="请输入应用私钥"
          ></el-input>
        </el-form-item>

        <el-form-item label="应用公钥" prop="publicKey">
          <el-input
            v-model="dbForm.publicKey"
            clearable
            :rows="5"
            type="textarea"
            placeholder="请输入应用公钥"
          ></el-input>
        </el-form-item>

        <el-form-item label="阿里支付公钥" prop="alipayPublicKey">
          <el-input
            v-model="dbForm.alipayPublicKey"
            clearable
            :rows="5"
            type="textarea"
            placeholder="请输入阿里支付公钥"
          ></el-input>
        </el-form-item>

        <el-form-item label="接口内容加密方式" prop="encryptKey">
          <el-input
            v-model="dbForm.encryptKey"
            clearable
            placeholder="请输入接口内容加密方式"
          ></el-input>
        </el-form-item>

        <el-form-item label="结果回调URL" prop="notifyUrl">
          <el-input v-model="dbForm.notifyUrl" clearable placeholder="请输入结果回调URL"></el-input>
        </el-form-item>

        <el-form-item label="前端返回URL" prop="returnUrl">
          <el-input v-model="dbForm.returnUrl" clearable placeholder="请输入前端返回URL"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="handleClose()">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()"> 提 交 </el-button>
    </template>
  </tw-drawer>
</template>

<script lang="ts" setup>
  import { ElMessage } from 'element-plus'
  import { assign, cloneDeep } from 'lodash-es'
  import { TenantConfigModel } from '/@/api/system/model/tenantConfigModel'
  import {
    apiTenantConfigGetByType,
    apiTenantConfigSave,
    apiTenantConfigUpdateById
  } from '/@/api/system/tenantConfig'
  import { isEmpty, isNotEmpty } from '/@/utils/isUtils'
  import { log } from '/@/utils/log'

  const loading = ref(true)

  /**
   * 显示弹框
   */
  const visible = ref(false)

  const dbFormRef = ref()

  //////////////////////////////////////////////////
  // 表单
  //////////////////////////////////////////////////

  const defaultForm = {
    appId: '', // 应用ID
    protocol: 'https', // 协议
    gatewayHost: '', // 网管主机
    signType: '', // 签名类型
    privateKey: '', // 应用私钥
    publicKey: '', // 应用公钥
    alipayPublicKey: '', // 阿里支付公钥
    encryptKey: '', // 接口内容加密方式
    notifyUrl: '', // 支付异步回调地址
    returnUrl: '' // 支付成功前端返回地址
  }

  let dbForm = reactive(cloneDeep(defaultForm))

  /**
   * 查询的配置信息
   */
  let configForm: TenantConfigModel = {}

  //////////////////////////////////////////////////
  // 表单验证规则
  //////////////////////////////////////////////////

  /**
   * 表单验证规则
   */
  const rules = reactive({
    appId: [
      {
        required: true,
        message: '请输入应用ID',
        trigger: 'blur'
      }
    ],
    protocol: [
      {
        required: true,
        message: '请输入协议',
        trigger: 'blur'
      }
    ],
    gatewayHost: [
      {
        required: true,
        message: '请输入网管主机',
        trigger: 'blur'
      }
    ],
    signType: [
      {
        required: true,
        message: '请输入签名类型',
        trigger: 'blur'
      }
    ],
    privateKey: [
      {
        required: true,
        message: '请输入应用私钥',
        trigger: 'blur'
      }
    ],
    publicKey: [
      {
        required: true,
        message: '请输入应用公钥',
        trigger: 'blur'
      }
    ],
    alipayPublicKey: [
      {
        required: true,
        message: '请输入阿里支付公钥',
        trigger: 'blur'
      }
    ],
    encryptKey: [
      {
        required: true,
        message: '请输入接口内容加密方式',
        trigger: 'blur'
      }
    ],
    notifyUrl: [
      {
        required: true,
        message: '请输入结果回调URL',
        trigger: 'blur'
      }
    ],
    returnUrl: [
      {
        required: true,
        message: '请输入前端返回URL',
        trigger: 'blur'
      }
    ]
  })

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 打开弹框
   */
  function handleOpen() {
    visible.value = true
    handleSearch()
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    dbForm = reactive(cloneDeep(defaultForm))
    visible.value = false
  }

  /**
   * 查询配置信息
   */
  function handleSearch() {
    loading.value = true
    apiTenantConfigGetByType('PAY_ALI')
      .then((result) => {
        if (result?.success) {
          configForm = result.data
          if (isNotEmpty(configForm.configJson)) {
            assign(dbForm, { remark: configForm.remark }, JSON.parse(configForm.configJson || ''))
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 提交表单
   */
  function handleSubmit() {
    const config: any = cloneDeep(dbForm)

    const submitParams = {
      id: configForm.id,
      unionId: dbForm.appId,
      configType: 'PAY_ALI',
      name: '支付宝支付',
      configJson: JSON.stringify(config)
    }

    dbFormRef.value.validate((valid: boolean) => {
      if (valid) {
        if (isEmpty(configForm.id)) {
          addFun(submitParams)
        } else {
          editFun(submitParams)
        }
      } else {
        log.warn('支付宝支付配置', '表单校验失败')
      }
    })
  }

  /**
   * 新增
   * @param isContinue 是否新增并继续
   */
  function addFun(submitParams) {
    loading.value = true
    apiTenantConfigSave(submitParams)
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
          handleClose()
        } else {
          ElMessage.error(result?.message)
        }
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 编辑
   * @returns
   */
  function editFun(submitParams) {
    loading.value = true
    apiTenantConfigUpdateById(submitParams)
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
          handleClose()
        } else {
          ElMessage.error(result?.message)
        }
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  //////////////////////////////////////////////////
  // 暴露出去，父组件才可以调用到
  //////////////////////////////////////////////////
  defineExpose({
    handleOpen
  })
</script>

<style scoped lang="scss">
  .form-wrapper {
    padding: 10px;
  }
</style>
